/*
* @Author: dengjiayao
* @Date:   2017-08-28 17:19:29
* @Last Modified by:   dengjiayao
* @Last Modified time: 2017-10-24 11:01:14
*/
import { modal } from 'vue-strap'
import DatePicker from 'vue-datepicker'
import getDatePickerOption from '../../util/date-picker-option'
import {
  showMsg,
  getAnnouncementList,
  addAnnouncement,
  updateAnnouncement
} from '../../vuex/action'

export default {
  data() {
    return {
      showModal: false,
      actionType: 'ADD', // ADD or UPDATE
      form: {
        market: '1',
        position: '0',
        content: '',
        url: '',
        type: '0',
        validBeginTime: '',
        validEndTime: ''
      },
      datePickerOption: getDatePickerOption()
    }
  },
  components: {
    'vue-modal': modal,
    'vue-date-picker': DatePicker
  },
  vuex: {
    actions: {
      xShowMsg: showMsg,
      xGetList: getAnnouncementList,
      xAdd: addAnnouncement,
      xUpdate: updateAnnouncement
    }
  },
  methods: {
    valid() {
      let fields = ['market', 'content', 'validBeginTime', 'validEndTime']
      for (let k of fields) {
        let v = this.form[k] + ''
        if (v.length === 0) {
          return Promise.reject({
            error_msg: '*标识的均为必填项'
          })
        }
      }
      if (this.form.validEndTime <= this.form.validBeginTime) {
        return Promise.reject({
          error_msg: '开始时间应早于结束时间'
        })
      }
      return Promise.resolve()
    },
    submit() {
      this.valid()
        .then(() => {
          if (this.actionType === 'ADD') {
            return this.xAdd(this.form)
          } else {
            return this.xUpdate(this.form)
          }
        })
        .then(() => {
          this.showModal = false
        })
        .catch(res => {
          this.xShowMsg({
            type: 'danger',
            content: res.error_msg
          })
        })
    }
  }
}
